﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
using System.Net;
using System.IO;
using System.Data;

namespace showcolat
{
    public partial class Recherche : Form
    {
        private int nombreMagique;
        //List<Serie> serieListe;
        List<Serie> listeSerie;
        int i=0;
        public Recherche()
        {
            InitializeComponent();
            
            nombreMagique = this.Controls.Count;       
        }
        public static string GetPageAsString(Uri address)
        {
            string result = "";

            // Create the web request  
            HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;

            // Get response  
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                // Get the response stream  
                StreamReader reader = new StreamReader(response.GetResponseStream());

                // Read the whole contents and return as a string  
                result = reader.ReadToEnd();
            }

            return result;
        }

        public static DataSet FetchXml(string uri)
        {
            // Create the web request  
            HttpWebRequest request
                = WebRequest.Create(uri) as HttpWebRequest;

            // Get response  
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                // Load data into a dataset  
                DataSet dsSeries = new DataSet();
                dsSeries.ReadXml(response.GetResponseStream());
                // Print dataset information  
                return dsSeries;
                //return PrintDataSet(dsSeries);
            }
        }

        public static List<Serie> FindSerie(string uri)
        {
            int i = 0;
            List<Serie> liste = new List<Serie>();
     
            DataSet series = FetchXml(uri);
            foreach (DataTable table in series.Tables)
            {
                foreach (DataRow row in table.Rows)
                {
                    if (row["Language"].ToString() == "fr")
                        if (i++ < 5)
                            liste.Add(GetInfoSerie(int.Parse(row["seriesid"].ToString())));
                }
            }
            return liste;
        }

        public static Serie GetInfoSerie(int id)
        {
            DataSet serie = FetchXml("http://www.thetvdb.com//data/series/" + id + "/fr.xml");
            string nom = serie.Tables[0].Rows[0]["SeriesName"].ToString();
            string resume = serie.Tables[0].Rows[0]["Overview"].ToString();
            string note = serie.Tables[0].Rows[0]["Rating"].ToString();
            string chaine=serie.Tables[0].Rows[0]["Network"].ToString();
            int duree = int.Parse(serie.Tables[0].Rows[0]["Runtime"].ToString());
            string h_diff = serie.Tables[0].Rows[0]["Airs_time"].ToString();
            string diffusion = serie.Tables[0].Rows[0]["Airs_DayOfWeek"].ToString();
            string genre = serie.Tables[0].Rows[0]["genre"].ToString();
            return new Serie(
                id,
                nom,
                0,
                resume,
                note,diffusion,chaine,h_diff,duree,genre);
        }

        public static List<Episode> FindEpisode(string NumEpisode)
        {
            List<Episode> liste = new List<Episode>();
            int i = 0;
            DataSet episodes = FetchXml("http://www.thetvdb.com//data/series/" + NumEpisode + "/all/fr.xml");
            foreach (DataTable table in episodes.Tables)
            {
                if (table.TableName == "Episode")
                {
                    foreach (DataRow row in table.Rows)
                    {
                        int EpisodeId = int.Parse(row["id"].ToString());
                        int SeasonNumber = int.Parse(row["Combined_season"].ToString());
                        string EpisodeNumber = row["Combined_episodenumber"].ToString();
                        int EpisodeLength = 0;
                        string EpisodeName = row["EpisodeName"].ToString();
                        string EpisodeRating = row["Rating"].ToString();
                        string Diffusion = row["FirstAired"].ToString();
                        liste.Add(new Episode(EpisodeId, EpisodeName, EpisodeNumber, SeasonNumber, EpisodeLength, int.Parse(NumEpisode), Diffusion));
                        if (i == 5)
                        {
                            Console.ReadKey(true);
                            i = 0;
                        }
                    }
                }
            }
            return liste;
        }


        public static void PrintDataSet(DataSet ds)
        {
            int i = 0;
            List<Serie> liste = new List<Serie>(5);
            // Print out all tables and their columns  
            foreach (DataTable table in ds.Tables)
            {
               
                Console.WriteLine("TABLE '{0}'", table.TableName);
                Console.WriteLine("Total # of rows: {0}", table.Rows.Count);
                Console.WriteLine("---------------------------------------------------------------");

                foreach (DataColumn column in table.Columns)
                {
                    Console.WriteLine("- {0} ({1})", column.ColumnName, column.DataType.ToString());
                }   


                Console.WriteLine(System.Environment.NewLine);

            } 
        }

        static string convertUri(string serie)
        {
            return "http://www.thetvdb.com/api/GetSeries.php?seriesname=" + serie + "&language=fr";
        }

        private void nomSerie_Click(object sender, EventArgs e)
        {
            while (this.Controls.Count > nombreMagique)
            {
                this.Controls.RemoveAt(nombreMagique);
                i = 0;
            }

            //List<Serie> listeSerie;
            string recherche = "";
            recherche = textBox_rech.Text;
            listeSerie = FindSerie(convertUri(recherche));            
            Label lab_serie;
            int y = 50;
            
            if (listeSerie.Count() == 0)
            {
                MessageBox.Show("aucune serie correspondante");
            }
            else
            {
                foreach (Serie s in listeSerie)
                {
                    this.Controls.Add(lab_serie = new Label
                    {
                        Name = i.ToString()/*s.NumSerie.ToString()*/,
                        AutoSize = true,
                        Location = new Point(100, y),
                        Text = s.NomSerie.ToString()+" / "+ s.NumSerie.ToString(),
                        Size = new System.Drawing.Size(200, 50),
                        Font = new Font("Arial", 10)
                    });
                    y += 50;
                    i++;
                    lab_serie.Click += new EventHandler(lab_serie_Click);                    
                }
            }
            //serieListe = listeSerie;
        }

        private void lab_serie_Click(object sender, EventArgs e)
        {
            Label l = (Label)sender;
            i = Convert.ToInt32(l.Name.ToString());
            //this.Text = i.ToString()+" / "+listeSerie[i];
            Form_description Serie = new Form_description(listeSerie[i]);
            Serie.ShowDialog();
        }

        private void idSerie_Click(object sender, EventArgs e)
        {  
            List<Episode> listeEpisode;
            string recherche_ep = "";
            recherche_ep = textBox_id_serie.Text;
            listeEpisode = FindEpisode(recherche_ep);
            Label episode;
            int y = 50;
            if (listeEpisode.Count == 0)
            {
                MessageBox.Show("aucune serie correspondante");
            }
            else
            {
                foreach (Episode ep in listeEpisode)
                {
                    this.Controls.Add(episode = new Label
                    {
                        Name = ep.IDEpisode.ToString(),
                        AutoSize = true,
                        Location = new Point(400, y),
                        Text = ep.ToString(),
                        Size = new System.Drawing.Size(200, 50),
                        Font = new Font("Arial", 10)
                    });
                    y += 50;
                }
            }
        }
    }
}
